package cn.terminus.service.customer.custominfo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.terminus.biz.customer.contractinfo.ContractInfoManager;
import cn.terminus.biz.customer.custombusiness.CustomBusinessManager;
import cn.terminus.biz.customer.custombusinessinfo.CustomBusinessInfoManager;
import cn.terminus.biz.customer.customcontacts.CustomContactsManager;
import cn.terminus.biz.customer.customdemand.CustomDemandManager;
import cn.terminus.biz.customer.customdemandarea.CustomDemandAreaManager;
import cn.terminus.biz.customer.custominfo.CustomInfoManager;
import cn.terminus.biz.customer.customlabel.CustomLabelManager;
import cn.terminus.biz.customer.customleaseinfo.CustomLeaseInfoManager;
import cn.terminus.biz.customer.custompurposeroom.CustomPurposeRoomManager;
import cn.terminus.biz.customer.userrecordinfo.UserRecordInfoManager;
import cn.terminus.client.customer.analysis.param.CustomerStageParam;
import cn.terminus.client.customer.analysis.result.CustomerNatureIndustryResult;
import cn.terminus.client.customer.analysis.result.CustomerNatureIndustryResultList;
import cn.terminus.client.customer.analysis.result.CustomerStageNumResult;
import cn.terminus.client.customer.customdemandarea.result.CustomDemandAreaResult;
import cn.terminus.client.customer.custominfo.param.*;
import cn.terminus.client.customer.custominfo.result.ChannelCustomerNumberResult;
import cn.terminus.client.customer.custominfo.result.CustomInfoByNameResult;
import cn.terminus.client.customer.custominfo.result.CustomInfoResult;
import cn.terminus.client.customer.custominfo.service.CustomInfoService;
import cn.terminus.client.customer.userrecordinfo.param.AddUserRecordInfoParam;
import cn.terminus.common.customer.bean.analysis.CustomerAnalysisDto;
import cn.terminus.common.customer.bean.analysis.CustomerNatureIndustryNumResultDto;
import cn.terminus.common.customer.bean.analysis.CustomerStageDto;
import cn.terminus.common.customer.bean.analysis.CustomerStageNumResultDto;
import cn.terminus.common.customer.bean.custombusiness.dto.CustomBusinessNewDto;
import cn.terminus.common.customer.bean.custombusinessinfo.dto.CustomBusinessInfoNewDto;
import cn.terminus.common.customer.bean.customcontacts.dto.CustomContactsDeleteDto;
import cn.terminus.common.customer.bean.customcontacts.dto.CustomContactsNewDto;
import cn.terminus.common.customer.bean.customdemand.dto.CustomDemandDeleteDto;
import cn.terminus.common.customer.bean.customdemand.dto.CustomDemandNewDto;
import cn.terminus.common.customer.bean.customdemandarea.dto.CustomDemandAreaDeleteDto;
import cn.terminus.common.customer.bean.customdemandarea.dto.CustomDemandAreaNewDto;
import cn.terminus.common.customer.bean.custominfo.dto.*;
import cn.terminus.common.customer.bean.customlabel.dto.CustomLabelDeleteDto;
import cn.terminus.common.customer.bean.customlabel.dto.CustomLabelNewDto;
import cn.terminus.common.customer.bean.customleaseinfo.dto.CustomLeaseInfoDeleteDto;
import cn.terminus.common.customer.bean.customleaseinfo.dto.CustomLeaseInfoNewDto;
import cn.terminus.common.customer.bean.custompurposeroom.dto.CustomPurposeRoomDeleteDto;
import cn.terminus.common.customer.bean.custompurposeroom.dto.CustomPurposeRoomNewDto;
import cn.terminus.common.customer.bean.custompurposeroom.dto.CustomPurposeRoomResultDto;
import cn.terminus.common.customer.bean.userrecordinfo.dto.UserRecordInfoDeleteDto;
import cn.terminus.common.customer.bean.userrecordinfo.dto.UserRecordInfoNewDto;
import cn.terminus.common.customer.constant.*;
import cn.terminus.result.common.annotation.TerminusParamVilidator;
import cn.terminus.result.common.context.TerminusCallContext;
import cn.terminus.result.common.exception.DataAccessException;
import cn.terminus.result.common.exception.ServiceException;
import cn.terminus.result.common.page.TerminusPageAble;
import cn.terminus.result.common.page.TerminusPageInfo;
import cn.terminus.result.common.result.TerminusResult;
import cn.terminus.result.common.util.BeanCopyUtils;
import cn.terminus.service.customer.analysis.OverviewAnalysis;
import cn.terminus.service.customer.common.AbstractTerminusService;
import cn.terminus.service.customer.feign.carrier.CarrierFeignClient;
import cn.terminus.service.customer.feign.carrier.ProjectRoomDetailResult;
import cn.terminus.service.customer.feign.channel.ChannelFeignClient;
import cn.terminus.service.customer.feign.dict.*;
import cn.terminus.service.customer.kafka.KafkaCustomerChannelParam;
import cn.terminus.service.customer.kafka.KafkaCustomerParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * (CustomInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-07-08 11:18:50
 */
@Service
public class CustomInfoServiceImpl extends AbstractTerminusService implements CustomInfoService {

    /**
     * 日志
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private CustomInfoManager customInfoManager;

    @Resource
    private CustomContactsManager customContactsManager;

    @Resource
    private CustomLabelManager customLabelManager;
    @Resource
    private CustomDemandAreaManager customDemandAreaManager;
    @Resource
    private CustomDemandManager customDemandManager;
    @Resource
    private CustomBusinessInfoManager customBusinessInfoManager;
    @Resource
    private CustomBusinessManager customBusinessManager;
    @Resource
    private CustomLeaseInfoManager customLeaseInfoManager;
    @Resource
    private CustomPurposeRoomManager customPurposeRoomManager;
    @Resource
    private UserRecordInfoManager userRecordInfoManager;
    @Resource
    DictFeignClient dictFeignClient;
    @Resource
    CarrierFeignClient carrierFeignClient;
    @Resource
    private ContractInfoManager contractInfoManager;
    @Resource
    private ChannelFeignClient channelFeignClient;

    /**
     * 主表单个新增
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<String> add(CustomInfoNewParam param, TerminusCallContext context) throws ServiceException {
        CustomInfoNewDto newDto = new CustomInfoNewDto();
        BeanCopyUtils.copyProperties(param, context, newDto);
        newDto.setId(genUUID());
        try {
            customInfoManager.add(newDto);
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(String.valueOf(newDto.getId()));
    }

    private Long saveCustomerBaseInfo(TerminusCallContext context, AddCustomInfoDto addCustomInfoDto) throws ServiceException {
        try {
            //保存基本信息
            CustomInfoNewDto customInfoNewDto = new CustomInfoNewDto();
            CustomInfoNewDto customInfoNewForm = addCustomInfoDto.getCustomInfoNewForm();
            if (!BeanUtil.isEmpty(customInfoNewForm)) {
                BeanCopyUtils.copyProperties(customInfoNewForm, customInfoNewDto);
                customInfoNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
                customInfoNewDto.setId(addCustomInfoDto.getId());
                customInfoNewDto.setStatus(true);
                customInfoNewDto.setSettledStatus(false);
                customInfoNewDto.setCreateTime(context.getCallTime());
                customInfoNewDto.setLastUpdateTime(context.getCallTime());
                customInfoManager.add(customInfoNewDto);
                //保存联系人
                List<CustomContactsNewDto> contactsNewFormList = addCustomInfoDto.getCustomContactsNewList();
                List<CustomContactsNewDto> list = new ArrayList<>();
                if (!CollUtil.isEmpty(contactsNewFormList)) {
                    for (CustomContactsNewDto customContactsDto : contactsNewFormList) {
                        CustomContactsNewDto customContactsNewDto = new CustomContactsNewDto();
                        BeanCopyUtils.copyProperties(customContactsDto, customContactsNewDto);
                        customContactsNewDto.setType(CustomPurposeRoomTypeEnum.CUSTOMER_MANAGER.getCode());
                        customContactsNewDto.setType(CustomContactsTypeEnum.CUSTOMER_MANAGER.getCode());
                        customContactsNewDto.setCboCustomId(addCustomInfoDto.getId());
                        customContactsNewDto.setId(genUUID());
                        customContactsNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
                        customContactsNewDto.setCreateTime(context.getCallTime());
                        customContactsNewDto.setCreateUser(context.getUser().getCallerName());
                        list.add(customContactsNewDto);
                    }
                    customContactsManager.addMulti(list);
                }
                //保存客户标签
                List<String> customLabel = addCustomInfoDto.getCboCustomLabel();
                List<CustomLabelNewDto> labelNewDtoList = new ArrayList<>();
                if (!CollUtil.isEmpty(customLabel)) {
                    for (String lable : customLabel) {
                        CustomLabelNewDto customLabelNewDto = new CustomLabelNewDto();
                        BeanCopyUtils.copyProperties(addCustomInfoDto, customLabelNewDto);
                        customLabelNewDto.setCboCustomLabel(lable);
                        customLabelNewDto.setCboCustomId(addCustomInfoDto.getId());
                        customLabelNewDto.setId(genUUID());
                        customLabelNewDto.setCreateTime(context.getCallTime());
                        customLabelNewDto.setCreateUser(context.getUser().getCallerName());
                        labelNewDtoList.add(customLabelNewDto);
                    }
                    customLabelManager.addMulti(labelNewDtoList);
                }
                return addCustomInfoDto.getId();
            } else {
                return null;
            }
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    private TerminusResult<String> saveDemandInfo(TerminusCallContext context, AddCustomInfoDto addCustomInfoDto) throws DataAccessException, ServiceException {
        CustomDemandNewDto customDemandNewDto = new CustomDemandNewDto();
        CustomDemandNewDto customDemandNewForm = addCustomInfoDto.getCustomDemandNewForm();
        if (!BeanUtil.isEmpty(customDemandNewForm)) {
            BeanCopyUtils.copyProperties(customDemandNewForm, customDemandNewDto);
            customDemandNewDto.setId(genUUID());
            customDemandNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
            customDemandNewDto.setCboCustomId(addCustomInfoDto.getId());
            customDemandNewDto.setCreateTime(context.getCallTime());
            customDemandNewDto.setCreateUser(context.getUser().getCallerName());
            customDemandManager.add(customDemandNewDto);

            List<CustomDemandAreaNewDto> areaNewFormList = addCustomInfoDto.getCustomDemandAreaNewList();
            List<CustomDemandAreaNewDto> areaNewDtoList = new ArrayList<>();
            if (!CollUtil.isEmpty(areaNewFormList)) {
                for (CustomDemandAreaNewDto areaNewDto : areaNewFormList) {
                    if ((!BeanUtil.isEmpty(areaNewDto.getCboCustomType()) && BeanUtil.isEmpty(areaNewDto.getCboCustomArea())) ||
                            (BeanUtil.isEmpty(areaNewDto.getCboCustomType()) && !BeanUtil.isEmpty(areaNewDto.getCboCustomArea()))) {
                        return TerminusResult.fail("410012", this.getMessage("410012"));
                    }
                    CustomDemandAreaNewDto demandAreaNewDto = new CustomDemandAreaNewDto();
                    BeanCopyUtils.copyProperties(areaNewDto, demandAreaNewDto);
                    demandAreaNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
                    demandAreaNewDto.setCboCustomDemandId(customDemandNewDto.getId());
                    demandAreaNewDto.setId(genUUID());
                    demandAreaNewDto.setCboCustomId(addCustomInfoDto.getId());
                    demandAreaNewDto.setCreateTime(context.getCallTime());
                    demandAreaNewDto.setCreateUser(context.getUser().getCallerName());
                    areaNewDtoList.add(demandAreaNewDto);
                }
                customDemandAreaManager.addMulti(areaNewDtoList);
            }
        }
        return null;
    }

    private void saveBussinessInfo(TerminusCallContext context, AddCustomInfoDto addCustomInfoDto) throws DataAccessException {
        CustomBusinessInfoNewDto customBusinessInfoNewDto = new CustomBusinessInfoNewDto();
        CustomBusinessInfoNewDto customBusinessInfoNewForm = addCustomInfoDto.getCustomBusinessInfoNewForm();
        if (!BeanUtil.isEmpty(customBusinessInfoNewForm)) {
            BeanCopyUtils.copyProperties(customBusinessInfoNewForm, customBusinessInfoNewDto);
            customBusinessInfoNewDto.setType(CustomBusinessInfoTypeEnum.CUSTOMER_MANAGER.getCode());
            customBusinessInfoNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
            customBusinessInfoNewDto.setId(genUUID());
            customBusinessInfoNewDto.setCreateTime(context.getCallTime());
            customBusinessInfoNewDto.setCreateUser(context.getUser().getCallerName());
            customBusinessInfoManager.add(customBusinessInfoNewDto);

            CustomBusinessNewDto customBusinessNewDto = new CustomBusinessNewDto();
            BeanCopyUtils.copyProperties(addCustomInfoDto, customBusinessNewDto);
            customBusinessNewDto.setId(genUUID());
            customBusinessNewDto.setCboCustomId(addCustomInfoDto.getId());
            customBusinessNewDto.setCboCustomBusinessId(customBusinessInfoNewDto.getId());
            customBusinessNewDto.setCreateTime(context.getCallTime());
            customBusinessNewDto.setCreateUser(context.getUser().getCallerName());
            customBusinessManager.add(customBusinessNewDto);
        }
    }

    private void saveLeaseInfo(TerminusCallContext context, AddCustomInfoDto addCustomInfoDto) throws DataAccessException {
        CustomLeaseInfoNewDto customLeaseInfoNewDto = new CustomLeaseInfoNewDto();
        CustomLeaseInfoNewDto customLeaseInfoNewForm = addCustomInfoDto.getCustomLeaseInfoNewForm();
        if (!BeanUtil.isEmpty(customLeaseInfoNewForm)) {
            BeanCopyUtils.copyProperties(customLeaseInfoNewForm, customLeaseInfoNewDto);
            customLeaseInfoNewDto.setId(genUUID());
            customLeaseInfoNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
            customLeaseInfoNewDto.setCboCustomId(addCustomInfoDto.getId());
            customLeaseInfoNewDto.setCreateTime(context.getCallTime());
            customLeaseInfoNewDto.setCreateUser(context.getUser().getCallerName());
            customLeaseInfoManager.add(customLeaseInfoNewDto);
        }
    }

    private TerminusResult<String> savePurposeRoom(TerminusCallContext context, AddCustomInfoDto addCustomInfoDto) throws DataAccessException, ServiceException {
        List<CustomPurposeRoomNewDto> purposeRoomNewDtoList = addCustomInfoDto.getPurposeRoomNewList();
        List<CustomPurposeRoomNewDto> customPurposeRoomNewDtoList = new ArrayList<>();
        if (!CollUtil.isEmpty(purposeRoomNewDtoList)) {
            purposeRoomNewDtoList = purposeRoomNewDtoList.stream().distinct().collect(Collectors.toList());
            for (CustomPurposeRoomNewDto purposeRoomNewDto : purposeRoomNewDtoList) {
                if ((BeanUtil.isEmpty(purposeRoomNewDto.getCboProjectId()) && !BeanUtil.isEmpty(purposeRoomNewDto.getCboRoomId()))
                        || (BeanUtil.isEmpty(purposeRoomNewDto.getCboProjectId()) && !BeanUtil.isEmpty(purposeRoomNewDto.getCboRoomId()))
                ) {
                    return TerminusResult.fail("410011", this.getMessage("410011"));
                }
                CustomPurposeRoomNewDto customPurposeRoomNewDto = new CustomPurposeRoomNewDto();
                BeanCopyUtils.copyProperties(purposeRoomNewDto, customPurposeRoomNewDto);
                customPurposeRoomNewDto.setId(genUUID());
                customPurposeRoomNewDto.setBusinessId(addCustomInfoDto.getBusinessId());
                customPurposeRoomNewDto.setType(CustomPurposeRoomTypeEnum.CUSTOMER_MANAGER.getCode());
                customPurposeRoomNewDto.setCboCustomId(addCustomInfoDto.getId());
                customPurposeRoomNewDto.setCreateTime(context.getCallTime());
                customPurposeRoomNewDtoList.add(customPurposeRoomNewDto);
            }
            customPurposeRoomManager.addMulti(customPurposeRoomNewDtoList);
        }
        return null;
    }

    public Integer queryByCustomName(String customerName, TerminusCallContext context) throws ServiceException {
        CustomInfoGetsDto dto = new CustomInfoGetsDto();
        dto.setCboCustomName(customerName);
        dto.setBusinessId(context.getBusiness().getBusinessId());
        try {
            Integer num = customInfoManager.queryByCustomName(dto);
            return num;
        } catch (DataAccessException e) {
            logger.error("校验名称是否唯一失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 新增客户
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<String> addDetail(AddCustomInfoParam param, TerminusCallContext context) throws ServiceException {
        AddCustomInfoDto addCustomInfoDto = new AddCustomInfoDto();
        BeanCopyUtils.queryCopyProperties(param, context, addCustomInfoDto);
        addCustomInfoDto.setId(genUUID());

        Long cboChannelUser = null;
        CustomInfoNewParam customInfoNewForm = param.getCustomInfoNewForm();
        if (BeanUtil.isNotEmpty(customInfoNewForm)) {
            Integer query = queryByCustomName(customInfoNewForm.getCboCustomName(), context);
            if (query != null) {
                return TerminusResult.fail("410015", this.getMessage("410015"));
            }
            cboChannelUser = customInfoNewForm.getCboChannelUser();
        }
        try {

            //保存基本信息
            Long id = saveCustomerBaseInfo(context, addCustomInfoDto);
            if (id == null || id < 1) {
                return TerminusResult.fail("410001", this.getMessage("410001"));
            }
            //保存需求信息
            saveDemandInfo(context, addCustomInfoDto);
            //保存工商信息
            saveBussinessInfo(context, addCustomInfoDto);
            //保存租赁信息
            saveLeaseInfo(context, addCustomInfoDto);
            //保存意向房源
            savePurposeRoom(context, addCustomInfoDto);

            //发送概览kafka
            logger.info("send overview 1");
            this.sendOverviewKafka(new OverviewAnalysis(context, 1, null));
            //新增客户发送kafka
            CompletableFuture.runAsync(() -> this.sendCustomerKafka(KafkaCustomerParam.setCustomerMessage(context, param.getCustomInfoNewForm().getCboCustomIndustry(), param.getCustomInfoNewForm().getCboCustomNature(), 1)));
            //新增客户关联渠道联系人发送kafka
            Long finalCboChannelUser = cboChannelUser;
            CompletableFuture.runAsync(() -> sendAddCustomerChannelMessage(context, finalCboChannelUser));
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(String.valueOf(addCustomInfoDto.getId()));
    }


    private void sendAddCustomerChannelMessage(TerminusCallContext context, Long cboChannelUser) {
        if (cboChannelUser != null) {
            this.sendChannelKafka(KafkaCustomerChannelParam.setCustomerChannelMessage(context, cboChannelUser, 1, StatusEnum.EDIT.getCode()));
        }

    }

    @Override
    public TerminusResult<String> addUserRecordInfo(AddUserRecordInfoParam param, TerminusCallContext context) throws ServiceException {
        UserRecordInfoNewDto newDto = new UserRecordInfoNewDto();
        BeanCopyUtils.queryCopyProperties(param, context, newDto);
        newDto.setId(genUUID());
        newDto.setCreateTime(context.getCallTime());
        newDto.setCreateUser(context.getUser().getCallerName());
        try {
            userRecordInfoManager.add(newDto);
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(String.valueOf(newDto.getId()));
    }


    /**
     * 更新
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> update(CustomInfoEditParam param, TerminusCallContext context) throws ServiceException {
        CustomInfoEditDto editDto = new CustomInfoEditDto();
        BeanCopyUtils.queryCopyProperties(param, context, editDto);
        try {
            Long id = param.getId();
            GetCustomInfoByNameResultDto detail = customInfoManager.getDetailById(id);

            //修改基本信息
            CustomInfoNewDto customInfoNewForm = editDto.getCustomInfoNewForm();
            if (!BeanUtil.isEmpty(customInfoNewForm)) {
                customInfoNewForm.setId(editDto.getId());
                if (customInfoNewForm.getCboChannelUser() != null) {
                    customInfoNewForm.setLastUpdateTime(context.getCallTime());
                }
                customInfoNewForm.setLastUpdateUser(context.getUser().getCallerName());
                customInfoManager.update(customInfoNewForm);
            }
            //修改标签信息
            List<String> cboCustomLabel = editDto.getCboCustomLabel();
            List<CustomLabelNewDto> labelNewDtoList = new ArrayList<>();
            CustomLabelDeleteDto deleteDto = new CustomLabelDeleteDto();
            deleteDto.setCboCustomId(editDto.getId());
            customLabelManager.delete(deleteDto);
            //不传标签字段则为null,不更改
            if (!BeanUtil.isEmpty(cboCustomLabel)) {
                for (String lable : cboCustomLabel) {
                    CustomLabelNewDto customLabelNewDto = new CustomLabelNewDto();
                    BeanCopyUtils.copyProperties(editDto, customLabelNewDto);
                    customLabelNewDto.setCboCustomLabel(lable);
                    customLabelNewDto.setCboCustomId(editDto.getId());
                    customLabelNewDto.setId(genUUID());
                    customLabelNewDto.setLastUpdateTime(context.getCallTime());
                    customLabelNewDto.setLastUpdateUser(context.getUser().getCallerName());
                    labelNewDtoList.add(customLabelNewDto);
                }

                //置空判断
                if (!CollUtil.isEmpty(labelNewDtoList)) {
                    customLabelManager.addMulti(labelNewDtoList);
                }
            }
            //修改联系人
            CustomContactsDeleteDto customContactsDeleteDto = new CustomContactsDeleteDto();
            customContactsDeleteDto.setCboCustomId(editDto.getId());
            customContactsManager.delete(customContactsDeleteDto);
            List<CustomContactsNewDto> customContactsList = editDto.getCustomContactsNewList();
            List<CustomContactsNewDto> customContactsNewList = new ArrayList<>();
            if (!BeanUtil.isEmpty(customContactsList)) {
                for (CustomContactsNewDto customContactsDto : customContactsList) {
                    CustomContactsNewDto customContactsNewDto = new CustomContactsNewDto();
                    BeanCopyUtils.copyProperties(customContactsDto, customContactsNewDto);
                    customContactsNewDto.setType(CustomContactsTypeEnum.CUSTOMER_MANAGER.getCode());
                    customContactsNewDto.setCboCustomId(editDto.getId());
                    customContactsNewDto.setId(genUUID());
                    customContactsNewDto.setBusinessId(editDto.getBusinessId());
                    customContactsNewDto.setLastUpdateTime(context.getCallTime());
                    customContactsNewDto.setLastUpdateUser(context.getUser().getCallerName());
                    customContactsNewList.add(customContactsNewDto);
                }
                if (!CollUtil.isEmpty(customContactsNewList)) {
                    customContactsManager.addMulti(customContactsNewList);
                }
            }
            //删除需求信息
            CustomDemandDeleteDto customDemandDeleteDto = new CustomDemandDeleteDto();
            customDemandDeleteDto.setCboCustomId(editDto.getId());
            customDemandManager.delete(customDemandDeleteDto);
            CustomDemandNewDto customDemandNewForm = editDto.getCustomDemandNewForm();
            if (!BeanUtil.isEmpty(customDemandNewForm)) {
                //新增需求信息
                CustomDemandNewDto customDemandNewDto = new CustomDemandNewDto();
                BeanCopyUtils.copyProperties(customDemandNewForm, customDemandNewDto);
                customDemandNewDto.setId(genUUID());
                customDemandNewDto.setBusinessId(editDto.getBusinessId());
                customDemandNewDto.setCboCustomId(editDto.getId());
                customDemandManager.add(customDemandNewDto);
            }

            //删除需求面积
            CustomDemandAreaDeleteDto customDemandAreaDeleteDto = new CustomDemandAreaDeleteDto();
            customDemandAreaDeleteDto.setCboCustomId(editDto.getId());
            customDemandAreaManager.delete(customDemandAreaDeleteDto);
            List<CustomDemandAreaNewDto> areaNewFormList = editDto.getCustomDemandAreaNewList();
            List<CustomDemandAreaNewDto> areaNewDtoList = new ArrayList<>();
            if (!BeanUtil.isEmpty(areaNewFormList)) {
                for (CustomDemandAreaNewDto areaNewDto : areaNewFormList) {
                    CustomDemandAreaNewDto demandAreaNewDto = new CustomDemandAreaNewDto();
                    BeanCopyUtils.copyProperties(areaNewDto, demandAreaNewDto);
                    demandAreaNewDto.setBusinessId(editDto.getBusinessId());
                    demandAreaNewDto.setId(genUUID());
                    demandAreaNewDto.setCboCustomId(editDto.getId());
                    demandAreaNewDto.setLastUpdateTime(context.getCallTime());
                    demandAreaNewDto.setLastUpdateUser(context.getUser().getCallerName());
                    areaNewDtoList.add(demandAreaNewDto);
                }
                if (!CollUtil.isEmpty(areaNewDtoList)) {
                    customDemandAreaManager.addMulti(areaNewDtoList);
                }
            }
            //修改工商信息
//            if (!BeanUtil.isEmpty(editDto.getCustomBusinessInfoNewForm())) {
//                Long bussinessId = customBusinessInfoManager.getBussinessId(editDto.getId());
//                editDto.getCustomBusinessInfoNewForm().setId(bussinessId);
//                editDto.getCustomBusinessInfoNewForm().setBusinessId(editDto.getBusinessId());
//                editDto.getCustomBusinessInfoNewForm().setLastUpdateTime(context.getCallTime());
//                editDto.getCustomBusinessInfoNewForm().setLastUpdateUser(context.getUser().getCallerName());
//                customBusinessInfoManager.update(editDto.getCustomBusinessInfoNewForm());
//            }
            //删除租赁信息
            CustomLeaseInfoDeleteDto customLeaseInfoDeleteDto = new CustomLeaseInfoDeleteDto();
            customLeaseInfoDeleteDto.setCboCustomId(editDto.getId());
            customLeaseInfoManager.delete(customLeaseInfoDeleteDto);
            CustomLeaseInfoNewDto customLeaseInfoNewForm = editDto.getCustomLeaseInfoNewForm();
            if (!BeanUtil.isEmpty(customLeaseInfoNewForm)) {
                //新增租赁信息
                CustomLeaseInfoNewDto customLeaseInfoNewDto = new CustomLeaseInfoNewDto();
                BeanCopyUtils.copyProperties(customLeaseInfoNewForm, customLeaseInfoNewDto);
                customLeaseInfoNewDto.setId(genUUID());
                customLeaseInfoNewDto.setBusinessId(editDto.getBusinessId());
                customLeaseInfoNewDto.setCboCustomId(editDto.getId());
                customLeaseInfoManager.add(customLeaseInfoNewDto);
            }
            //修改意向房源
            CustomPurposeRoomDeleteDto customPurposeRoomDeleteDto = new CustomPurposeRoomDeleteDto();
            customPurposeRoomDeleteDto.setCboCustomId(editDto.getId());
            customPurposeRoomDeleteDto.setType(CustomPurposeRoomTypeEnum.CUSTOMER_MANAGER.getCode());
            customPurposeRoomManager.deleteByCustomerId(customPurposeRoomDeleteDto);
            List<CustomPurposeRoomNewDto> purposeRoomNewDtoList = editDto.getPurposeRoomNewList();
            List<CustomPurposeRoomNewDto> customPurposeRoomNewDtoList = new ArrayList<>();
            if (!BeanUtil.isEmpty(purposeRoomNewDtoList)) {
                purposeRoomNewDtoList = purposeRoomNewDtoList.stream().distinct().collect(Collectors.toList());
                for (CustomPurposeRoomNewDto purposeRoomNewDto : purposeRoomNewDtoList) {
                    CustomPurposeRoomNewDto customPurposeRoomNewDto = new CustomPurposeRoomNewDto();
                    BeanCopyUtils.copyProperties(purposeRoomNewDto, customPurposeRoomNewDto);
                    customPurposeRoomNewDto.setId(genUUID());
                    customPurposeRoomNewDto.setBusinessId(editDto.getBusinessId());
                    customPurposeRoomNewDto.setType(CustomPurposeRoomTypeEnum.CUSTOMER_MANAGER.getCode());
                    customPurposeRoomNewDto.setCboCustomId(editDto.getId());
                    customPurposeRoomNewDto.setLastUpdateTime(context.getCallTime());
                    customPurposeRoomNewDto.setLastUpdateUser(context.getUser().getCallerName());
                    customPurposeRoomNewDtoList.add(customPurposeRoomNewDto);
                }

                if (!CollUtil.isEmpty(customPurposeRoomNewDtoList)) {
                    customPurposeRoomManager.addMulti(customPurposeRoomNewDtoList);
                }
            }
            //修改跟进记录
            UserRecordInfoDeleteDto userRecordInfoDeleteDto = new UserRecordInfoDeleteDto();
            userRecordInfoDeleteDto.setCboCustomerId(editDto.getId());
            userRecordInfoManager.delete(userRecordInfoDeleteDto);
            List<UserRecordInfoNewDto> userRecordInfoList = editDto.getUserRecordInfoEditList();
            List<UserRecordInfoNewDto> userRecordInfoNewList = new ArrayList<>();
            if (!BeanUtil.isEmpty(userRecordInfoList)) {
                for (UserRecordInfoNewDto userRecordInfoDto : userRecordInfoList) {
                    UserRecordInfoNewDto userRecordInfoNewDto = new UserRecordInfoNewDto();
                    BeanCopyUtils.copyProperties(userRecordInfoDto, userRecordInfoNewDto);
                    userRecordInfoNewDto.setId(genUUID());
                    userRecordInfoNewDto.setBusinessId(editDto.getBusinessId());
                    userRecordInfoNewDto.setCboCustomerId(editDto.getId());
                    userRecordInfoNewDto.setLastUpdateTime(context.getCallTime());
                    userRecordInfoNewDto.setLastUpdateUser(context.getUser().getCallerName());
                    userRecordInfoNewList.add(userRecordInfoNewDto);
                }
                if (!CollUtil.isEmpty(userRecordInfoNewList)) {
                    userRecordInfoManager.addMulti(userRecordInfoNewList);
                }
            }

            //编辑客户发送kafka
            CompletableFuture.runAsync(() -> {
                if (!BeanUtil.isEmpty(detail)) {
                    this.sendCustomerKafka(KafkaCustomerParam.setCustomerMessage(context, detail.getCboCustomIndustry(), detail.getCboCustomNature(), -1));
                    this.sendCustomerKafka(KafkaCustomerParam.setCustomerMessage(context, param.getCustomInfoNewForm().getCboCustomIndustry(), param.getCustomInfoNewForm().getCboCustomNature(), 1));
                }
            });
            //编辑客户关联渠道联系人发送kafka
            String beforeChannelUser = detail.getCboChannelUser();
            CompletableFuture.runAsync(() -> sendUpdateCustomerChannelMessage(param, beforeChannelUser, context));
        } catch (DataAccessException e) {
            logger.error("更新失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }

    private void sendUpdateCustomerChannelMessage(CustomInfoEditParam param, String beforeChannelUser, TerminusCallContext context) {
        if (beforeChannelUser != null) {
            this.sendChannelKafka(KafkaCustomerChannelParam.setCustomerChannelMessage(context, Long.parseLong(beforeChannelUser), -1, StatusEnum.EDIT.getCode()));
        }
        Long afterChannelUser = param.getCustomInfoNewForm().getCboChannelUser();
        if (afterChannelUser != null) {
            this.sendChannelKafka(KafkaCustomerChannelParam.setCustomerChannelMessage(context, afterChannelUser, 1, StatusEnum.EDIT.getCode()));
        }
    }

//    private KafkaCustomerChannelParam getCustomerChannelById(Long cboChannelUser) {
//        KafkaCustomerChannelParam kafkaCustomerChannelParam = new KafkaCustomerChannelParam();
//        ChannelUserInfoGetsForm form = new ChannelUserInfoGetsForm();
//        form.setIds(Arrays.asList(String.valueOf(cboChannelUser)));
//        TerminusResult<List<ChannelUserInfoResult>> result = channelFeignClient.gets(form);
//        List<ChannelUserInfoResult> data = result.getData();
//        ChannelUserInfoResult channelUserInfoResult1 = new ChannelUserInfoResult();
//        if (CollUtil.isNotEmpty(data)) {
//            channelUserInfoResult1 = data.get(0);
//        }
//        //渠道来源
//        String cboChannelSource = channelUserInfoResult1.getCboChannelSource();
//        String cboChannelNameCode = channelUserInfoResult1.getCboChannelName();
//        String cboChannelPerson = channelUserInfoResult1.getCboChannelPerson();
//        String channelResourceName = null;
//        String cboChannelName = null;
//        Map<String, String> channelSourceDict = getDictByDictCode(DictCodeConstant.CHANNELSOURCE);
//        Map<String, String> channelNameDict = getAllChannelName(DictCodeConstant.CHANNELSOURCE);
//        if (BeanUtil.isNotEmpty(channelSourceDict)) {
//            //渠道来源描述
//            channelResourceName = channelSourceDict.get(cboChannelSource);
//        }
//        if (BeanUtil.isNotEmpty(channelNameDict)) {
//            //渠道名称
//            cboChannelName = channelNameDict.get(cboChannelNameCode);
//        }
//        kafkaCustomerChannelParam.setChannelPersonName(cboChannelPerson);
//        kafkaCustomerChannelParam.setChannelPersonId(cboChannelUser);
//        kafkaCustomerChannelParam.setChannelResource(cboChannelSource);
//        kafkaCustomerChannelParam.setChannelResourceName(channelResourceName);
//        kafkaCustomerChannelParam.setChannelName(cboChannelName);
//        return kafkaCustomerChannelParam;
//    }

    /**
     * 删除
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> delete(CustomInfoDeleteParam param, TerminusCallContext context) throws ServiceException {
        CustomInfoDeleteDto deleteDto = new CustomInfoDeleteDto();
        BeanCopyUtils.queryCopyProperties(param, context, deleteDto);
        try {
            List<CustomInfoBaseDto> list = customInfoManager.getBaseCustomerInfoByIds(param.getIds());

            Integer countNum = contractInfoManager.getByCustomerIdList(deleteDto.getIds());
            if (countNum > 0) {
                return TerminusResult.fail("410018", this.getMessage("410018"));
            }
            //发送删除客户kafka
            CompletableFuture.runAsync(() -> {
                sendDeleteCustomerKafkaMessage(list, context);
            });

            //发送删除客户关联渠道联系人kafka
            CompletableFuture.runAsync(() -> {
                sendDeleteCustomerChannelMessage(list, context);
            });
            customInfoManager.delete(deleteDto);
        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }

    private void sendDeleteCustomerChannelMessage(List<CustomInfoBaseDto> list, TerminusCallContext context) {
        if (!CollUtil.isEmpty(list)) {
            for (CustomInfoBaseDto customInfoBaseDto : list) {
                Long cboChannelUser = customInfoBaseDto.getCboChannelUser();
                if (cboChannelUser != null) {
                    this.sendChannelKafka(KafkaCustomerChannelParam.setCustomerChannelMessage(context, cboChannelUser, -1, StatusEnum.EDIT.getCode()));
                }
            }
        }
    }

    private void sendDeleteCustomerKafkaMessage(List<CustomInfoBaseDto> list, TerminusCallContext context) {
        Map<String, List<CustomInfoBaseDto>> map = new HashMap<>();
        if (!CollUtil.isEmpty(list)) {
            //发送概览kafka，客户删，入驻企业也删
            this.sendOverviewKafka(new OverviewAnalysis(context, -list.size(), null));
            int i = 0;
            for (CustomInfoBaseDto customInfoBaseDto : list) {
                if (customInfoBaseDto.getSettledStatus() == 1) {
                    i++;
                }
            }
            this.sendOverviewKafka(new OverviewAnalysis(context, null, -i));
            for (CustomInfoBaseDto customInfoBaseDto : list) {
                String key = customInfoBaseDto.getCboCustomIndustry() + "-" + customInfoBaseDto.getCboCustomNature();
                List<CustomInfoBaseDto> keyList = map.get(key);
                if (CollUtil.isEmpty(keyList)) {
                    List<CustomInfoBaseDto> newList = new ArrayList<>();
                    newList.add(customInfoBaseDto);
                    map.put(key, newList);
                } else {
                    keyList.add(customInfoBaseDto);
                }
            }
            for (List<CustomInfoBaseDto> value : map.values()) {
                for (CustomInfoBaseDto customInfoBaseDto : value) {
                    this.sendCustomerKafka(KafkaCustomerParam.setCustomerMessage(context, customInfoBaseDto.getCboCustomIndustry(), customInfoBaseDto.getCboCustomNature(), -1));
                }
            }
        }
    }

    @Override
    public TerminusResult<CustomInfoResult> getDetail(CustomInfoGetsParam param, TerminusCallContext context) throws ServiceException {
        CustomInfoGetsDto getsDto = new CustomInfoGetsDto();
        BeanCopyUtils.queryCopyProperties(param, context, getsDto);
        try {
            CustomInfoResultDto customInfoResultDto = customInfoManager.getDetail(getsDto);
            if (BeanUtil.isEmpty(customInfoResultDto)) {
                return null;
            }
            List<CustomPurposeRoomResultDto> roomList = customInfoResultDto.getCustomPurposeRoomList();
            if (!CollUtil.isEmpty(roomList)) {
                List<Long> roomIdList = roomList.stream().map(e -> e.getCboRoomId()).collect(Collectors.toList());
                List<ProjectRoomDetailResult> projectRoomDetailResultList = carrierFeignClient.getDetailByIds(roomIdList).getData();
                roomList = roomList.stream().map(e -> {
                    if (!CollUtil.isEmpty(projectRoomDetailResultList)) {
                        for (ProjectRoomDetailResult roomDetailResult : projectRoomDetailResultList) {
                            if (roomDetailResult.getId().longValue() == e.getCboRoomId()) {
                                BeanCopyUtils.copyProperties(roomDetailResult, e);
                                e.setCboProjectName(roomDetailResult.getProjectName());
                                e.setCboProjectBuildName(roomDetailResult.getBuildName());
                                e.setCboProjectBuildFloorName(roomDetailResult.getBuildFloorName());
                            }
                        }
                    }

                    return e;

                }).collect(Collectors.toList());
            }

            customInfoResultDto.setCustomPurposeRoomList(roomList);
            return TerminusResult.success(BeanCopyUtils.copyProperties(customInfoResultDto, CustomInfoResult.class));
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 分页查询
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    public TerminusResult<TerminusPageAble<CustomInfoResult>> page(CustomInfoQueryParam param, TerminusPageInfo page, TerminusCallContext context) throws ServiceException {
        CustomInfoQueryDto queryDto = new CustomInfoQueryDto();
        BeanCopyUtils.queryCopyProperties(param, context, queryDto);
        try {

            TerminusPageAble<CustomInfoResultDto> TerminusPageAble = customInfoManager.page(queryDto, page);
            Collection<CustomInfoResultDto> datas = TerminusPageAble.getDatas();
            if (CollectionUtils.isEmpty(datas)) {
                return TerminusResult.success(new TerminusPageAble<>(new ArrayList<>(), page, 0));
            }
            List<CustomInfoResult> list = BeanCopyUtils.copy(datas, CustomInfoResult.class);
            if (CollUtil.isEmpty(list)) {
                return TerminusResult.success(new TerminusPageAble<>(new ArrayList<>(), page, 0));
            }
            transferDictCodeToName(list);
            return TerminusResult.success(new TerminusPageAble<>(BeanCopyUtils.copy(list, CustomInfoResult.class),
                    page, TerminusPageAble.getTotalRows()));
        } catch (DataAccessException e) {
            logger.error("分页查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    public void transferDictCodeToName(List<CustomInfoResult> list) {
        Map<String, String> channelNameDict = getAllChannelName(DictCodeConstant.CHANNELSOURCE);
        Map<String, String> channelSourceDict = getDictByDictCode(DictCodeConstant.CHANNELSOURCE);

        Map<String, String> customIndustryDict = getDictByDictCode(DictCodeConstant.CUSTOMINDUSTRY);
        Map<String, String> demandTypeDict = getDictByDictCode(DictCodeConstant.DEMANDTYPE);
        //字典值code转换为name返回
        list.stream().forEach(info -> {
            // 渠道名称字典code->name
            if (channelNameDict != null && channelNameDict.size() > 0) {
                String channelName = channelNameDict.get(info.getCustomInfoBaseDto().getCboChannelName());
                if (channelName != null) {
                    info.getCustomInfoBaseDto().setCboChannelName(channelName);
                }
            }
            //渠道来源code->name
            if (channelSourceDict != null && channelSourceDict.size() > 0) {
                String channelSource = channelSourceDict.get(info.getCustomInfoBaseDto().getCboChannelSource());
                if (channelSource != null) {
                    info.getCustomInfoBaseDto().setCboChannelSource(channelSource);
                }
            }
            //客户行业code->name
            if (customIndustryDict != null && customIndustryDict.size() > 0) {
                String customIndustry = customIndustryDict.get(info.getCustomInfoBaseDto().getCboCustomIndustry());
                if (customIndustry != null) {
                    info.getCustomInfoBaseDto().setCboCustomIndustry(customIndustry);
                }
            }
            //需求类型code->name
            if (demandTypeDict != null && demandTypeDict.size() > 0) {
                List<CustomDemandAreaResult> customDemandAreaList = info.getCustomDemandAreaList();
                if (!CollUtil.isEmpty(customDemandAreaList)) {
                    for (CustomDemandAreaResult demandAreaResult : customDemandAreaList) {
                        String demandType = demandTypeDict.get(demandAreaResult.getCboCustomType());
                        if (demandType != null) {
                            demandAreaResult.setCboCustomType(demandType);
                        }
                    }
                }
            }
        });
    }

    public Map<String, String> getDictByDictCode(String code) {
        ItemQueryParam param = new ItemQueryParam().setDictCode(code);
        List<ItemResult> data = dictFeignClient.query(param).getData();
        if (data != null && data.size() > 0) {
            return data.stream().collect(Collectors.toMap(ItemResult::getDictKey, ItemResult::getDictValue, (v1, v2) -> v1));
        }
        return null;
    }

    public Map<String, String> getAllChannelName(String code) {
        ItemQueryParam param = new ItemQueryParam()
                .setDictCode(code);

        List<ItemResult> data = dictFeignClient.query(param).getData();
        if (data != null && data.size() > 0) {
            List<String> nameCode = data.stream().map(ItemResult::getDictKey).collect(Collectors.toList());
            ItemSearchParam searchParam = new ItemSearchParam();
            searchParam.setCodes(nameCode);
            TerminusResult<List<ItemListResult>> listTerminusResult = dictFeignClient.queryAll(searchParam);
            if (listTerminusResult.isSuccess()) {
                List<ItemListResult> results = listTerminusResult.getData();
                ArrayList<ItemResult> itemResults = new ArrayList<>();
                results.stream().forEach(r -> {
                    itemResults.addAll(r.getItems());
                });
                return itemResults
                        .stream()
                        .collect(Collectors.toMap(ItemResult::getDictKey, ItemResult::getDictValue, (v1, v2) -> v1));
            }
        }
        return null;
    }

    @Override
    public TerminusResult<Boolean> belongTo(CustomBelongtoParam param, TerminusCallContext context) throws ServiceException {
        CustomBelongtoDto customBelongtoDto = new CustomBelongtoDto();
        BeanCopyUtils.copyProperties(param, customBelongtoDto);
        try {
            customInfoManager.belongTo(customBelongtoDto);
        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }

    @Override
    public TerminusResult<List<CustomInfoByNameResult>> getNameListByName(GetNameListByNameParam param, TerminusCallContext context) throws ServiceException {
        GetCustomInfoByNameDto dto = new GetCustomInfoByNameDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            List<GetCustomInfoByNameResultDto> list = customInfoManager.getNameListByName(dto);
            return TerminusResult.success(BeanCopyUtils.copy(list, CustomInfoByNameResult.class));
        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    @Override
    public TerminusResult<List<ChannelCustomerNumberResult>> getChannelCustomerNumber(CustomerChannelUserParam param, TerminusCallContext context) throws ServiceException {
        CustomerChannelUserDto dto = new CustomerChannelUserDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            List<ChannelCustomerNumberResultDto> list = customInfoManager.getChannelCustomerNumber(dto);
            if (CollUtil.isEmpty(list)) {
                return TerminusResult.fail("410010", this.getMessage("410010"));
            }
            return TerminusResult.success(BeanCopyUtils.copy(list, ChannelCustomerNumberResult.class));
        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public TerminusResult<List<CustomerStageNumResult>> analysisStage(CustomerStageParam param, TerminusCallContext context) throws ServiceException {
        CustomerAnalysisDto dto = new CustomerAnalysisDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            List<CustomerStageNumResultDto> stageList = customInfoManager.analysisCustomerStage(dto);

            List<CustomerStageNumResult> resultDtoList = new ArrayList<>();

            Map<String, String> customStageDict = getDictByDictCode(DictCodeConstant.CUSTOMSTAGE);
            //字典值code转换为name返回
            stageList.stream().forEach(info -> {
                //客户行业code->name
                if (customStageDict != null && customStageDict.size() > 0) {
                    String customStage = customStageDict.get(info.getCboCustomerStage());
                    if (customStage != null) {
                        info.setCboCustomerStage(customStage);
                    }
                }
            });

            resultDtoList.addAll(BeanCopyUtils.copy(stageList, CustomerStageNumResult.class));
            if (CollUtil.isEmpty(resultDtoList)) {
                return null;
            }
            return TerminusResult.success(resultDtoList);
        } catch (DataAccessException e) {
            logger.error("获取客户统计数据失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public TerminusResult<CustomerNatureIndustryResultList> analysisNatureAndIndustry(CustomerStageParam param, TerminusCallContext context) throws ServiceException {
        CustomerStageDto dto = new CustomerStageDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            CustomerNatureIndustryResultList resultList = new CustomerNatureIndustryResultList();
            List<CustomerNatureIndustryNumResultDto> analysisNatureList = customInfoManager.analysisNature(dto);
            //排序
            analysisNatureList = analysisNatureList.stream().sorted(Comparator.comparing(CustomerNatureIndustryNumResultDto::getCustomerNature, (o1, o2) -> o1 == null ? 1 : (o2 == null ? -1 : o2.compareTo(o1)))).collect(Collectors.toList());

            List<CustomerNatureIndustryNumResultDto> analysisIndustryList = customInfoManager.analysisIndustry(dto);
            analysisIndustryList = analysisIndustryList.stream().sorted(Comparator.comparing(CustomerNatureIndustryNumResultDto::getCustomerIndustry, (o1, o2) -> o1 == null ? 1 : (o2 == null ? -1 : o2.compareTo(o1)))).collect(Collectors.toList());

            analysisNatureAndIndustryDictCodeToName(analysisNatureList, analysisIndustryList);

            resultList.setAnalysisNatureList(BeanCopyUtils.copy(analysisNatureList, CustomerNatureIndustryResult.class));
            resultList.setAnalysisIndustryList(BeanCopyUtils.copy(analysisIndustryList, CustomerNatureIndustryResult.class));
            return TerminusResult.success(resultList);
        } catch (DataAccessException e) {
            logger.error("获取客户统计数据失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public TerminusResult<List<ChannelCustomerNumberResult>> changeCustomerChannel(CustomerChannelUserParam param, TerminusCallContext context) throws ServiceException {
        CustomerChannelUserDto dto = new CustomerChannelUserDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            List<ChannelCustomerNumberResultDto> list = customInfoManager.getChannelCustomerNumber(dto);
            if (CollUtil.isEmpty(list)) {
                return TerminusResult.fail("410010", this.getMessage("410010"));
            }
            customInfoManager.changeCustomerChannel(dto);
            return TerminusResult.success(BeanCopyUtils.copy(list, ChannelCustomerNumberResult.class));
        } catch (DataAccessException e) {
            logger.error("置空删除渠道联系人的客户,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }


    public void analysisNatureAndIndustryDictCodeToName(List<CustomerNatureIndustryNumResultDto> analysisNatureList, List<CustomerNatureIndustryNumResultDto> analysisIndustryList) {
        Map<String, String> customIndustryDict = getDictByDictCode(DictCodeConstant.CUSTOMINDUSTRY);
        Map<String, String> customNatureDict = getDictByDictCode(DictCodeConstant.CUSTOMNATURE);
        analysisNatureList.stream().forEach(info -> {
            //客户性质code->name
            if (customNatureDict != null && customNatureDict.size() > 0) {
                String customNature = customNatureDict.get(info.getCustomerNature());
                if (customNature != null) {
                    info.setCustomerNature(customNature);
                }
            }
        });
        analysisIndustryList.stream().forEach(info -> {
            //客户行业code->name
            if (customIndustryDict != null && customIndustryDict.size() > 0) {
                String customIndustry = customIndustryDict.get(info.getCustomerIndustry());
                if (customIndustry != null) {
                    info.setCustomerIndustry(customIndustry);
                }
            }
        });

    }


}
